﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using ZXing;
using ZXing.QrCode;
using ZXing.QrCode.Internal;

public class GetQRCode 
{ 
    /// <summary>
    /// 扫描二维码
    /// </summary>
    /// <param name="webCamTexture"></param>获取摄像头内容
    /// <returns></returns>
    public static string ScanQRCode(WebCamTexture webCamTexture)
    {
        Color32[] data;
        //Zxing 读取内容
        BarcodeReader readReaderCode=new BarcodeReader();
        //获取图片上的颜色 
        data = webCamTexture.GetPixels32();
        // 存储读取的内容
        ZXing.Result result = readReaderCode.Decode(data, webCamTexture.width, webCamTexture.height);

        if (result != null)
            return result.Text; 
        return "data is error!";
    }
    /// <summary>
    /// 生成的二维码
    /// </summary>
    /// <param name="str"></param>显示内容
    /// <param name="width"></param>二维码的宽度
    /// <param name="height"></param>二维码的高度
    public static Texture2D CreatQRCode(string str, int width, int height)
    {
        //定义texture2d并且填充
        Texture2D t = new Texture2D(width, height);
        t.SetPixels32(GetColor32(str, width, height));
        t.Apply();
        return t; 
    }
    /// <summary>
    /// 返回Color32图片颜色
    /// </summary>
    /// <param name="str"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public static Color32[] GetColor32(string  str, int width, int height)
    {

        QrCodeEncodingOptions options = new QrCodeEncodingOptions();
        //可能是中文的状态下设置UTF-8编码,
        options.CharacterSet = "UTF-8"; 
        options.Width = width;
        options.Height = width;
        //设置二维码边缘的空白
        options.Margin = 1;

        BarcodeWriter writeCode = new BarcodeWriter { Format =  BarcodeFormat.QR_CODE, Options = options };

        return writeCode.Write(str);
    } 
}
